package com.lee.jdbc.dao.proc;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;

import com.lee.jdbc.Student;
import com.lee.jdbc.mappers.StudentMapper;

public class StudentJdbcProcTemplate implements StudentProDao {

	private DataSource dataSource;
	private SimpleJdbcCall jdbcCall;
	private JdbcTemplate jdbcTemplateObject;

	@Override
	public void setDataSource(DataSource ds) {
		dataSource = ds;
		jdbcTemplateObject = new JdbcTemplate(ds);
		jdbcCall = new SimpleJdbcCall(ds).withProcedureName("getRecord");
	}

	@Override
	public void create(String name, int age) {
		String sql = "insert into Student (name,age) values (?,?)";
		jdbcTemplateObject.update(sql, name, age);
		System.out.println("Created Record Name = " + name + ", Age = " + age);
	}

	@Override
	public Student getStudent(int id) {
		SqlParameterSource inParameterSource = new MapSqlParameterSource().addValue("in_id", id);
		Map<String, Object> out = jdbcCall.execute(inParameterSource);
		Student student = new Student();
		student.setId(id);
		student.setName((String) out.get("out_name"));
		student.setAge((int) out.get("out_age"));
		return student;
	}

	@Override
	public List<Student> listStudents() {
		String sql = "select * from Student";
		List<Student> students = jdbcTemplateObject.query(sql, new StudentMapper());
		return students;
	}

}
